<template>
    <div class="service-pack-form-container">
        <!-- 标题 -->
        <div class="form-header">
            <h3>服务包信息</h3>
        </div>

        <!-- 表单 -->
        <el-form :model="formData" :rules="formRules" label-width="120px" style="padding: 24px;" ref="formRef"
            class="service-pack-form">
            <el-row :gutter="20">
                <!-- 第一行 -->
                <el-col :span="8">
                    <el-form-item label="服务包名称" prop="name" required>
                        <el-input v-model="formData.name" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="服务包类型" prop="type" required>
                        <el-select v-model="formData.type" placeholder="请选择" style="width: 100%">
                            <el-option v-for="type in servicePackTypes" :key="type" :label="type" :value="type" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="订购价格" prop="price" required>
                        <div style="display: flex; align-items: center;">
                            <el-input v-model="formData.price" placeholder="请输入" style="flex: 1;" />
                            <span style="margin-left: 8px;">元/年</span>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 第二行 -->
                <el-col :span="8">
                    <el-form-item label="服务对象" prop="client" required>
                        <el-input v-model="formData.client" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="服务包标签" prop="tags">
                        <el-input v-model="formData.tags" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="签约周期" prop="contractPeriod">
                        <el-select v-model="formData.contractPeriod" placeholder="请选择" style="width: 100%">
                            <el-option label="1年" value="1年" />
                            <el-option label="2年" value="2年" />
                            <el-option label="3年" value="3年" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 第三行 -->
                <el-col :span="24">
                    <el-form-item label="续约情况">
                        <el-radio-group v-model="formData.renewalStatus">
                            <el-radio value="1">可续签</el-radio>
                            <el-radio value="0">不可续签</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 服务包图片 -->
                <el-col :span="24">
                    <el-form-item label="服务包图片">
                        <el-upload class="avatar-uploader"
                            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                            :show-file-list="false">
                            <img v-if="imageUrl" src="" class="avatar" />
                            <div v-else class="upload-placeholder">
                                <el-icon size="24" color="#ccc">
                                    <Plus />
                                </el-icon>
                                <div>上传图片</div>
                            </div>
                        </el-upload>
                        <div class="upload-tip">图片尺寸400*600px，可上传多张</div>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <!-- 服务介绍 -->
                <el-col :span="24">
                    <el-form-item label="服务介绍">
                        <el-input v-model="formData.intro" type="textarea" :rows="6" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 操作按钮 -->
            <div class="form-actions">
                <el-button type="primary" @click="handleSave" :loading="submitting">
                    {{ isEdit ? '更新' : '提交审核' }}
                </el-button>
                <el-button @click="handleCancel">返回</el-button>
            </div>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { findServicePacksApi } from '@/api/servicepack';
import { addServicePacksApi, updateServicePacksApi, getServicePacksDetailApi } from '@/api/doctors';

// 路由实例
const route = useRoute()
const router = useRouter()

// 表单引用
const formRef = ref()

// 提交状态
const submitting = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => route.path.includes('/update/'))

// 服务包类型列表
const servicePackTypes = ref<string[]>([])

// 图片上传
const imageUrl = ref('')

// 表单数据
const formData = ref({
    name: '',
    type: '',
    price: '',
    client: '',
    tags: '',
    contractPeriod: '',
    renewalStatus: '1',
    intro: '',
});

// 表单校验规则
const formRules = ref({
    name: [
        { required: true, message: '请输入服务包名称', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请输入服务包类型', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请输入订购价格', trigger: 'blur' }
    ],
    client: [
        { required: true, message: '请输入服务对象', trigger: 'blur' }
    ]
});

onMounted(() => {
    // 获取服务包类型数据
    loadServicePackTypes()

    // 如果是编辑模式，加载服务包数据
    if (isEdit.value) {
        loadServicePackData()
    }
})

// 获取服务包类型数据
async function loadServicePackTypes() {
    const res = await findServicePacksApi({
        currentPage: 1,
        pageSize: 200
    })

    if (res.code === 200) {
        // 从服务包数据中提取唯一的类型
        const types = new Set(res.data.rows.map((item: any) => item.type))
        servicePackTypes.value = Array.from(types) as string[]
    } else {
        ElMessage.error(res.message)
    }

}

// 加载服务包数据（编辑模式）
async function loadServicePackData() {
    const id = route.params._id as string
    if (!id) {
        ElMessage.error('缺少服务包ID')
        return
    }

    console.log('加载服务包数据，ID:', id)

    const res = await getServicePacksDetailApi({ _id: id })
    console.log('服务包详情API响应:', res)

    if (res.code === 200) {
        const data = res.data
        formData.value = {
            name: data.name || '',
            type: data.type || '',
            price: data.price || '',
            client: data.client || '',
            tags: data.tags || '',
            contractPeriod: data.period || '',
            renewalStatus: data.renew !== undefined ? String(data.renew) : '1',
            intro: data.intro || '',
        }

        // 设置图片预览
        if (data.image) {
            imageUrl.value = data.image
        }

        ElMessage.success('服务包数据加载成功')
    } else {
        ElMessage.error(res.message || '加载服务包数据失败')
    }
}

// 保存表单
const handleSave = async () => {
    if (!formRef.value) return

    await formRef.value.validate()

    submitting.value = true

    if (isEdit.value) {
        // 编辑模式：调用更新接口
        const updateData = {
            ...formData.value,
            _id: route.params._id
        }
        console.log('更新服务包数据:', updateData)

        const res = await updateServicePacksApi(updateData)
        console.log('更新服务包API响应:', res)

        if (res.code === 200) {
            ElMessage.success('更新服务包成功！')
            // 跳转回列表页
            router.push('/data/servicePack/list')
        } else {
            ElMessage.error(res.message || '更新服务包失败')
        }
    } else {
        // 新增模式：调用新增接口
        console.log('新增服务包数据:', formData.value)

        const res = await addServicePacksApi(formData.value)
        console.log('新增服务包API响应:', res)

        if (res.code === 200) {
            ElMessage.success('新增服务包成功！')
            // 跳转回列表页
            router.push('/data/servicePack/list')
        } else {
            ElMessage.error(res.message || '新增服务包失败')
        }
    }

    submitting.value = false
};

// 返回
const handleCancel = () => {
    router.push('/data/servicePack/list')
};

</script>

<style scoped>
.search-container {
    padding: 20px 0;
    background: #fff;
    border-radius: 4px;
}

.textitem {
    position: relative;
    padding-left: 20px;
}

.textitem::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 6px;
    height: 20px;
    background-color: rgba(41, 132, 248, 1);
    border-radius: 8px;
}

.form-row {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
}

.form-row>.el-form-item {
    margin-right: 0;
    margin-left: 0;
}

.form-row>.el-form-item:not(:first-child) {
    margin-left: 24px;
}

.form-row:last-child {
    margin-bottom: 0;
}

.el-input {
    --el-input-bg-color: #fff;
    --el-input-border-color: #dcdfe6;
    --el-input-hover-border-color: #c0c4cc;
}

/* 图片上传样式 */
.avatar-uploader {
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;
    width: 400px;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.avatar-uploader:hover {
    border-color: #409eff;
}

.avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #999;
}

.upload-placeholder div {
    margin-top: 8px;
    font-size: 14px;
}

.upload-tip {
    font-size: 12px;
    color: #999;
    margin-top: 8px;
}
</style>
